package cn.leedsoft.luma.plugins.shiro;

import cn.leedsoft.luma.common.Constants;
import cn.leedsoft.luma.mapper.domain.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

public class ShiroUtils {

	public static Subject subject() {
		return SecurityUtils.getSubject();
	}

	public static User principal() {
		Subject subject = subject();
		return subject != null ? (User) subject.getPrincipal() : null;
	}

	//普通用户
	public static boolean isReaders(){
		if (user()) {
			return Constants.ROLE_READERS.indexOf("," + principal().getRoleId().toString() + ",") != -1;
		}
		return false;
	}
	
	// 作者
	public static boolean isAuthor() {
		if (user()) {
			return Constants.ROLE_AUTHOR.indexOf("," + principal().getRoleId().toString() + ",") != -1;
		}
		return false;
	}

	// 管理员判断
	public static boolean isAdmin() {
		if (user()) {
			return Constants.ROLE_ADMINS.indexOf("," + principal().getRoleId().toString() + ",") != -1;
		}
		return false;
	}

	// 超级管理员判断
	public static boolean isSuperAdmin() {
		if (user()) {
			return Constants.ROLE_ADMIN_SUPER.indexOf("," + principal().getRoleId().toString() + ",") != -1;
		}
		return false;
	}

	public static boolean isDev() {
		if (user()) {
			return Constants.ROLE_DEV.indexOf("," + principal().getRoleId().toString() + ",") != -1;
		}
		return false;
	}



	public static boolean user() {
		Subject subject = subject();
		return subject != null && subject.getPrincipal() != null;
	}

	public static boolean guest() {
		Subject subject = subject();
		return subject == null || subject.getPrincipal() == null;
	}

	public static boolean authenticated() {
		Subject subject = subject();
		return subject != null && subject.isAuthenticated();
	}

	public static boolean notAuthenticated() {
		Subject subject = subject();
		return subject == null || !subject.isAuthenticated();
	}

	public static boolean hasPermission(String permission) {
		Subject subject = subject();
		return subject != null ? subject.isPermitted(permission) : false;
	}

	public static boolean lacksPermission(String permission) {
		return !hasPermission(permission);
	}

	public static boolean hasRole(String role) {
		Subject subject = subject();
		return subject != null ? subject.hasRole(role) : false;
	}

	public static boolean lacksRole(String role) {
		return !hasRole(role);
	}
}
